package com.tedu.weibo.controller;

import com.tedu.weibo.mapper.WeiboMapper;
import com.tedu.weibo.pojo.dto.WeiboDTO;
import com.tedu.weibo.pojo.entity.User;
import com.tedu.weibo.pojo.entity.Weibo;
import com.tedu.weibo.pojo.vo.WeiboDetailVO;
import com.tedu.weibo.pojo.vo.WeiboIndexVO;
import com.tedu.weibo.result.JsonResult;
import com.tedu.weibo.result.Status;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.client.RestTemplate;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/v1/weibo")
@Api(tags = "微博模块")
@Validated
public class WeiboController {
    @Autowired
    private WeiboMapper weiboMapper;



    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @PostMapping("/insert")
    @ApiOperation(value = "发表微博")
    public JsonResult insert(@RequestBody WeiboDTO weiboDTO, @ApiIgnore HttpSession session){
        System.out.println("开始发表微博...");
        System.out.println(weiboDTO);
        User user= (User) session.getAttribute("user");
        if (user==null){
            return new JsonResult(Status.NOT_LOGIN);
        }
            Weibo weibo=new Weibo();
            weibo.setContent(weiboDTO.getContent());
            weibo.setCreated(new Date());
            weibo.setUserId(user.getId());
             weiboMapper.insert(weibo);
        return JsonResult.success();
    }
    @GetMapping("/selectIndex")
    @ApiOperation(value = "查看首页微博列表")
    public JsonResult findIndexWeibo(){
        ValueOperations ops = redisTemplate.opsForValue();
        List<WeiboIndexVO> list= (List<WeiboIndexVO>) ops.get("weiboList");
        if (list==null){
            list=weiboMapper.selectAll();
            ops.set("weiboList",list);
        }
        return JsonResult.success(list);
    }
    @GetMapping("/selectById")
    @ApiOperation(value = "查看指定微博")
    @ApiImplicitParam(name = "id",value = "微博id",required = true,example = "10", dataType = "int")
    public JsonResult findById(@Range(min = 1,max = 99999,message="微博ID必须在1-99999之间") @RequestParam Integer id){
//        if (id==null||id<0){
//            throw new IllegalArgumentException("微博ID不正确");
//        }
        return  JsonResult.success(weiboMapper.selectById(id));

    }
}
